#! /usr/bin/perl

use FindBin qw($Bin);
use lib "$Bin/../lib/";
use FileAIS;
use GO::OntologyProvider::OboParser;

unless (@ARGV==3) {
    print "perl $0 <organelle.conf> <obo> <children>\n";
    exit;
}

my ($conf,$obo,$out) = @ARGV;

my $conf_hash = &FileAIS::Open2Hash($conf,'organelle');


my $ontology = GO::OntologyProvider::OboParser->new(ontologyFile => $obo,aspect => 'C');
my @nodes = $ontology->allNodes;

my %hash;
foreach my $k (sort @nodes) {
    my $goid = $k->goid;
    my $children = '';
    foreach my $item (sort keys %{$k}){
        if ($item eq 'GO::Node::__children') {
            my @tmp = keys %{$k->{$item}};
            $hash{$goid} = \@tmp;
#            $children = join(',',keys %{$k->{$item}});
        }
   }
#    print "$goid\t$children\n";
}

my %out;
foreach my $organelle (keys %{$conf_hash}) {
    my $root = $conf_hash->{$organelle}->{'GO'};
    my @allChild;                                   # 数组
    &get_allChild(\%hash,$root,\@allChild);
    foreach my $item (@allChild) {
        $tmp{$item} = 1;
    }
    my @childs = keys %tmp;
    $out{$organelle}{'organelle'} = $organelle;
    $out{$organelle}{'GO'} = $root;
    $out{$organelle}{'childrens'} = join(',',@childs);

    # print "$organelle\t$root\t",join(',',@allChild),"\n";
}

&FileAIS::Hash2File(\%out,$out);
##############################################
sub get_allChild {
    my ($relate_hash,$root,$allChild_array) = @_;

    if (exists $relate_hash->{$root} && $relate_hash->{$root} ne ''){
        my @childs = @{$relate_hash->{$root}};
        if (scalar(@childs) > 0) {
            foreach my $child (@childs) {   
                push @{$allChild_array},$child;
                &get_allChild($relate_hash,$child,$allChild_array);
            }
        } else {
            return 1;
        }
    } else {
        return 1;
    }
}